import lombok.Data;

/**
 * @Author: wanqian
 * @Date: 2021/3/27 11:38
 */
@Data
public class LinkedList {
    private Node head = new Node();

    public void addByOrder(Node node) {
        Node temp = head;
        while (temp.getNext() != null) {
            if (temp.getNext().getValue() > node.getValue()) {
                break;
            }
            temp = temp.getNext();
        }
        node.setNext(temp.getNext());
        temp.setNext(node);
    }

    public void remove(int value) {
        if (isEmpty()) {
            return;
        }
        Node temp = this.head;
        while (temp.getNext() != null) {
            if (value == temp.getNext().getValue()) {
                temp.setNext(temp.getNext().getNext());
                return;
            }
            temp = temp.getNext();
        }
    }

    /**
     * @param lastIndex
     * @return
     */
    public Node getFromEnd(int lastIndex) {
        if (lastIndex < 0 || lastIndex >= this.length()) {
            return null;
        }

        Node temp = this.head;
        for (int i = 0; i < length() - lastIndex; i++) {
            temp = temp.getNext();
        }

        return temp;
    }

    public boolean isEmpty() {
        return head.getNext() == null;
    }

    public int length() {
        if (isEmpty()) {
            return 0;
        }
        int num = 0;
        Node temp = this.head.getNext();
        while (temp != null) {
            num++;
            temp = temp.getNext();
        }
        return num;
    }
}

@Data
class Node {

    private int value;

    private Node next;
}
